/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package it.polimi.games.epkb.controller;

import it.polimi.games.epkb.controller.exceptions.NonexistentEntityException;
import it.polimi.games.epkb.controller.exceptions.PreexistingEntityException;
import it.polimi.games.epkb.entityClasses.ActivityData;
import it.polimi.games.epkb.entityClasses.ActivityDataPK;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import it.polimi.games.epkb.entityClasses.DataFile;
import it.polimi.games.epkb.entityClasses.Activity;
import javax.transaction.UserTransaction;

/**
 *
 * @author plebani
 */
public class ActivityDataJpaController implements Serializable {

    public ActivityDataJpaController(EntityManagerFactory emf) {
        this.utx = null;
        this.emf = emf;
    }


    public ActivityDataJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(ActivityData activityData) throws PreexistingEntityException, Exception {
        if (activityData.getActivityDataPK() == null) {
            activityData.setActivityDataPK(new ActivityDataPK());
        }
        activityData.getActivityDataPK().setIdActivity(activityData.getActivity().getId());
        activityData.getActivityDataPK().setIdDataFile(activityData.getDataFile().getId());
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            DataFile dataFile = activityData.getDataFile();
            if (dataFile != null) {
                dataFile = em.getReference(dataFile.getClass(), dataFile.getId());
                activityData.setDataFile(dataFile);
            }
            Activity activity = activityData.getActivity();
            if (activity != null) {
                activity = em.getReference(activity.getClass(), activity.getId());
                activityData.setActivity(activity);
            }
            em.persist(activityData);
            if (dataFile != null) {
                dataFile.getActivityDataCollection().add(activityData);
                dataFile = em.merge(dataFile);
            }
            if (activity != null) {
                activity.getActivityDataCollection().add(activityData);
                activity = em.merge(activity);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            if (findActivityData(activityData.getActivityDataPK()) != null) {
                throw new PreexistingEntityException("ActivityData " + activityData + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(ActivityData activityData) throws NonexistentEntityException, Exception {
        activityData.getActivityDataPK().setIdActivity(activityData.getActivity().getId());
        activityData.getActivityDataPK().setIdDataFile(activityData.getDataFile().getId());
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            ActivityData persistentActivityData = em.find(ActivityData.class, activityData.getActivityDataPK());
            DataFile dataFileOld = persistentActivityData.getDataFile();
            DataFile dataFileNew = activityData.getDataFile();
            Activity activityOld = persistentActivityData.getActivity();
            Activity activityNew = activityData.getActivity();
            if (dataFileNew != null) {
                dataFileNew = em.getReference(dataFileNew.getClass(), dataFileNew.getId());
                activityData.setDataFile(dataFileNew);
            }
            if (activityNew != null) {
                activityNew = em.getReference(activityNew.getClass(), activityNew.getId());
                activityData.setActivity(activityNew);
            }
            activityData = em.merge(activityData);
            if (dataFileOld != null && !dataFileOld.equals(dataFileNew)) {
                dataFileOld.getActivityDataCollection().remove(activityData);
                dataFileOld = em.merge(dataFileOld);
            }
            if (dataFileNew != null && !dataFileNew.equals(dataFileOld)) {
                dataFileNew.getActivityDataCollection().add(activityData);
                dataFileNew = em.merge(dataFileNew);
            }
            if (activityOld != null && !activityOld.equals(activityNew)) {
                activityOld.getActivityDataCollection().remove(activityData);
                activityOld = em.merge(activityOld);
            }
            if (activityNew != null && !activityNew.equals(activityOld)) {
                activityNew.getActivityDataCollection().add(activityData);
                activityNew = em.merge(activityNew);
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                ActivityDataPK id = activityData.getActivityDataPK();
                if (findActivityData(id) == null) {
                    throw new NonexistentEntityException("The activityData with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(ActivityDataPK id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            ActivityData activityData;
            try {
                activityData = em.getReference(ActivityData.class, id);
                activityData.getActivityDataPK();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The activityData with id " + id + " no longer exists.", enfe);
            }
            DataFile dataFile = activityData.getDataFile();
            if (dataFile != null) {
                dataFile.getActivityDataCollection().remove(activityData);
                dataFile = em.merge(dataFile);
            }
            Activity activity = activityData.getActivity();
            if (activity != null) {
                activity.getActivityDataCollection().remove(activityData);
                activity = em.merge(activity);
            }
            em.remove(activityData);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<ActivityData> findActivityDataEntities() {
        return findActivityDataEntities(true, -1, -1);
    }

    public List<ActivityData> findActivityDataEntities(int maxResults, int firstResult) {
        return findActivityDataEntities(false, maxResults, firstResult);
    }

    private List<ActivityData> findActivityDataEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(ActivityData.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public ActivityData findActivityData(ActivityDataPK id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(ActivityData.class, id);
        } finally {
            em.close();
        }
    }

    public int getActivityDataCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<ActivityData> rt = cq.from(ActivityData.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
